#include "mywidget.h"
#include "ui_widget.h"
#include<QSharedPointer>
#include<QHostInfo>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget),
        m_server(new Server(this))
{

   ui->setupUi(this);
    plotShowTimer=new QTimer(this);
    addDataTimer=new QTimer(this);
    dataTextTimer=new QTimer(this);
    connect(plotShowTimer,SIGNAL(timeout()),this,SLOT(replotshow()));
    connect(addDataTimer,SIGNAL(timeout()),this,SLOT(dataChart()));

/****
*设置图标
*/
   setWindowTitle("TcpNet_Assistant V1.0.0");
    setWindowIcon(QIcon(":/pic/ICON.ico"));
//    setFixedSize(468,415);

/*
*样式表设置按钮风格
*/
    setStyleSheet(

         "QPushButton{"
         "background-color:#E8F3EE;"
          "border-style:outset;"
         "border-width:2px;"
         "border-radius:4px;"
         "border-color:#668074;"
         "color:#7B9589;"
         "}"

         "QPushButton:hover{"
         "background-color:#5f9ae6;"
         "color:white;"
         "}");


    ui->edit_ConnectIP->setText("No Connect");
    percent=0.5;


/*****
*设置窗口背景
*/
    QPixmap pixmapBackground = QPixmap(":/pic/backBlue.jpg").scaled(this->size());
    QPalette  palette (this->palette());
    palette.setBrush(QPalette::Background, QBrush(pixmapBackground));
    this-> setPalette( palette );


/***********
 * 界面初始化
*/
    QImage logo;
    logo.load(":/pic/logo.png");
    QPixmap pixmap = QPixmap::fromImage(logo);
    int with = ui->lab_Logo->width();
    int height = ui->lab_Logo->height();
    QPixmap fitpixmap = pixmap.scaled(with, height, Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    ui->lab_Logo->setPixmap(fitpixmap);
}

Widget::~Widget()
{
    delete ui;
}

/*/////////////////////
 * 函数名： void Widget::portplot(QCustomPlot *customplot)
 * 传入参数：customplot:QCustomPlot对象
 * 功能： 图像的初始化函数，并且设置x个曲线
 */
void Widget::portPlotInit(QCustomPlot *customplot)
{
    customplot->clearGraphs();
    //设置xy轴文字
    customplot->setNotAntialiasedElements(QCP::aeAll);
    QFont font;
    font.setStyleStrategy(QFont::NoAntialias);
    font.setPointSize(9);
    font.setBold(true);
    font.setWeight(100);

    customplot->xAxis->setTickLabelFont(font);
    customplot->yAxis->setTickLabelFont(font);
    customplot->legend->setFont(font);//图例

    //增加1个曲线
    customplot->addGraph();//增加一个图层
    customplot->graph(0)->setPen(QPen(Qt::red));
    customplot->graph(0)->setName("Channel one");


/*以时间的格式作为横坐标*/
    /*
    QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
    timeTicker->setTimeFormat("%h:%m:%s");
    customplot->xAxis->setTicker(timeTicker);
    */
    customplot->axisRect()->setupFullAxesBox();
    customplot->legend->setVisible(true);           //图例可见
    yAxismin=-2;
    yAxismax=2;
    customplot->yAxis->setRange(yAxismin,yAxismax);
    customplot->xAxis->setRange(0,XAXISMIN+6000*percent,Qt::AlignRight);
    customplot->replot();
    addDataTimer->start(DATA_ADD_INTERVAL);         //打开定时器

}

/*
 * 传入参数：clientIP：客户端IP tempSockDesc：套接字描述符
 * 功能：    连接状态显示
 */
void Widget::connectState(QString clientIP,int tempSockDesc)
{
    QString connectIP;
    int index;
    connectSockDesc=tempSockDesc;
    index=clientIP.lastIndexOf(":");                //找到“:”最后出现的index
    qDebug()<<"clientIP:"<<clientIP.mid(index+1);   //截取最后一个“:”后面的字符串
    connectIP=clientIP.mid(index+1);
    ui->edit_ConnectIP->setText(connectIP);
}
void Widget::disconnectState(int m_sockDesc)
{
    ui->edit_ConnectIP->setText("Disconnection");
    qDebug()<<"m_sockDesc disconnect:"<<m_sockDesc;
}

/*
 * 传入参数：无
 * 功能：   在坐标系中加点，但是先不显示
 */
void Widget::dataChart()
{
    QMutexLocker locker(&mutex);            //加锁，防止对缓冲区的通知访问
    int buff_size=m_server->recv_buffer.size();
//    qDebug()<<"size"<<buff_size;
    //当缓冲区的数据多时，读出固定个数的数据，缓冲区数据不多时，全部读出
    if(buff_size>=ONCE_READ_NUM)
    {
        for(int i=0;i<ONCE_READ_NUM;i++)
        {
             ui->plotwidget->graph(0)->addData(ui->plotwidget->graph(0)->dataCount(),m_server->recv_buffer.at(0)); //把数据增加到曲线上
             m_server->recv_buffer.removeAt(0);
        }
    }else
    {
        for(int i=0;i<buff_size;i++)
        {
             ui->plotwidget->graph(0)->addData(ui->plotwidget->graph(0)->dataCount(),m_server->recv_buffer.at(0)); //把数据增加到曲线上
             m_server->recv_buffer.removeAt(0);
        }
    }
}

void Widget::on_btn_Listen_clicked()
{
    port=ui->edit_Port->text().toInt();
    if(ui->btn_Listen->text()=="开始监听")
    {
        m_server->listen(QHostAddress::Any,port);
        ui->btn_Listen->setText("停止监听");
        qDebug()<<"start listen";
    }else
    {
        emit serverDisconnect();
        ui->btn_Listen->setText("开始监听");
    }


}
void Widget::on_btn_DataShow_clicked()
{
    if(ui->btn_DataShow->text()=="数据显示")
    {
        connect(dataTextTimer,SIGNAL(timeout()),this,SLOT(dataTextShow()));
        dataTextTimer->start(DATA_TEXT_INTERVAL);
        ui->btn_DataShow->setText("数据隐藏");
    }else
    {
        disconnect(dataTextTimer,SIGNAL(timeout()),this,SLOT(dataTextShow()));
        dataTextTimer->stop();
        ui->btn_DataShow->setText("数据显示");
    }


}
void Widget::on_btn_ChartShow_clicked()
{
    if(ui->btn_ChartShow->text()=="绘图显示")
    {
        portPlotInit(ui->plotwidget);
        plotShowTimer->start(REPLOT_TIMER_INTERVAL);
//        connect(this,SIGNAL(dataConverts(const QString &)),this,SLOT(dataChart(const QString &)));
        ui->btn_ChartShow->setText("隐藏绘图");
    }else
    {
        plotShowTimer->stop();
        ui->btn_ChartShow->setText("绘图显示");
    }

}

/*
 *  功能：横纵坐标调节
 *
 **/
void Widget::on_slider_X_sliderMoved(int position)
{
    qDebug()<<"position"<<position;
    percent=position/100.0;
        qDebug()<<"percent"<<percent;
}

void Widget::on_btn_SetChart_clicked()
{
    yAxismin=ui->edit_YMin->text().toFloat();
    yAxismax=ui->edit_YMax->text().toFloat();
    ui->plotwidget->yAxis->setRange(yAxismin,yAxismax);
    ui->plotwidget->replot();
}

/*
 * 参数：无
 * 功能：保存图片
*/

void Widget::on_pushButton_8_clicked()
{
   // QString fileName=QFileDialog::getOpenFileName(this,tr("save file"),"picture1.png",tr("Allfile(*.*);;pngfile(*.png)"));
    //使用QStringLiteral而不是双引号的普通C++的字符串可显著加快从编译时已知的数据创建QString实例的速度
    //打开路径，默认存储为“.png”格式
    QString fileName=QFileDialog::getSaveFileName(this,tr("save file"),QStringLiteral("E:/Qt_project/TcpNet_Assistant/pic"),QStringLiteral("PNG File(*.png)"));
    if(fileName.isEmpty())
    {
        QMessageBox::information(this,"Error Message","direction error");
        return;
    }
    ui->plotwidget->savePng(fileName,861,711);
    qDebug()<<fileName;
}
/*
 * 参数：无
 * 功能：保存数据接收区的数据
*/
void Widget::on_btn_SaveData_clicked()
{
    QString fileName=QFileDialog::getSaveFileName(this,tr("save file"),QStringLiteral("E:/Qt_project/TcpNet_Assistant/text"),QStringLiteral("txt(*.txt)"));
    if(fileName.isEmpty())
    {
        QMessageBox::information(this,"Error Message","direction error");
        return;
    }
    QFile file(fileName);
    bool ret=file.open(QIODevice::WriteOnly);
    if(ret)
    {
        QTextStream out(&file);
        QString text=ui->rec_TextBro->toPlainText();
        text.replace(QString("\n"),QString("\r\n"));    //把"\n"用"\r\n"代替
        out<<text;
        file.close();

    }else
    {
        QMessageBox::information(this,"Error Messaage","File Save Error");
        return;
    }
}
void Widget::on_btn_Clear_clicked()
{
    ui->rec_TextBro->clear();
}

void Widget::on_btn_Write_clicked()
{
    QString writeData;
    writeData=ui->edit_Send->toPlainText()+"\n";
    emit sentData(writeData.toUtf8());
}

void Widget::on_btn_SendClear_clicked()
{
    ui->edit_Send->clear();
}

/****
*功能:获取本机IP
*/
void Widget::on_btn_Search_clicked()
{
    QString localIP;
    QString localHostName = QHostInfo::localHostName();
    QHostInfo info = QHostInfo::fromName(localHostName);
  //  qDebug() <<"IP Address: "<<info.addresses();
    foreach(QHostAddress address,info.addresses())  //遍历整个容器
    {
         if(address.protocol() == QAbstractSocket::IPv4Protocol)
             localIP=address.toString();
    }
    //qDebug() << "localIP:"<<localIP;
    ui->edit_LocIP->setText(localIP);
}

/*
 * 参数：无
 * 功能：刷新显示图像
*/
void Widget::replotshow()
{
    ui->plotwidget->xAxis->setRange(ui->plotwidget->graph(0)->dataCount(),XAXISMIN+6000*percent,Qt::AlignRight);//qCeil为向上取整
    ui->plotwidget->replot(QCustomPlot::rpQueuedReplot);
}
/*
 * 参数：无
 * 功能：刷新显示文本
*/
void Widget::dataTextShow()
{
    QString tmp;
    //加锁，防止同时访问缓冲区，函数运行后，释放内存，自动解锁
    QMutexLocker locker(&mutex);
    int buff_size=m_server->recv_buffer.size();
    if(buff_size>=ONCE_READ_NUM)
    {
        for(int i=0;i<ONCE_READ_NUM;i++)
        {
            tmp=QString::number(m_server->recv_buffer.at(0)) ;
             ui->rec_TextBro->append(tmp);
             m_server->recv_buffer.removeAt(0);
        }
    }else
    {
        for(int i=0;i<buff_size;i++)
        {
            tmp=QString::number(m_server->recv_buffer.at(0)) ;

             ui->rec_TextBro->append(tmp);
             m_server->recv_buffer.removeAt(0);
        }
    }
}
